%% Data Logger 004 27/11/2012 BP
clear;

%% Define Serial Port Name
port = input ('Input Port Name  ','s');


%% Create & Open Serial Port
SER = serial(port,'Terminator','lf','baud',115200,'DataTerminalReady','off');
%%
fopen(SER);

%% Create Log File
log = input ('Input Log File Name  ','s');
fID=fopen([log,'.bin'],'w+');

%%
figure

%% Read Data

vals=500;

L=zeros(vals,7);
X=1:vals;

current_row=1;

H(6)=0;

for i=1:6
  subplot(2,3,i);
  H(i)=plot(X,zeros(1,500));
  ylim([0,1024]);
  xlim([0,500]);
end
%%
fwrite(SER,240);
%%
while 1
    t = fread(SER,1,'uint32');  %read line from serial
    S = fread(SER,6,'uint16');
    
    fwrite(fID,t,'uint32',0,'l');      		% Write data directly to a file
    fwrite(fID,S,'uint16',0,'l');
    %disp(current_row);
    L(current_row,:)=[t,S'];     %add data to new line in array
    
    % Get elements of L as a ring buffer
    R=[current_row+1:vals,1:current_row];
    
    for i=1:6
            set(H(i),'YData',L(R,i+1));
    end
    drawnow;                %force figure to redraw
    
    % Increment buffer position, loop back if at the end
    current_row=mod(current_row,vals)+1;
end


%When end function, end and fclose(SER) to close serial port before
%clearing variables.